<template>
  <div>
    <!-- <div v-for="(item, index) in blockList"> {{item.name}}  </div> -->
    <div id="olMap" class=""></div>
    <a-tooltip placement="left">
      <template slot="title">
        <span>圈地</span>
      </template>
      <div class="buttonClass but4" @click="addInteraction" v-show="isShow">
        <img :src="require(`@/assets/quan.png`)" class="back2" />
      </div>
    </a-tooltip>
    <a-tooltip placement="bottom">
      <template slot="title">
        <span>退出</span>
      </template>
      <div class="buttonClass goback-but" @click="goBack" v-show="isBack">
        <a-icon type="arrow-left" />
      </div>
    </a-tooltip>
    <a-tooltip placement="bottom">
      <template slot="title">
        <span>清空</span>
      </template>
      <div class="buttonClass clear" @click="clearClick" v-show="isClear">
        <img :src="require(`@/assets/clear.png`)" class="back3" />
      </div>
    </a-tooltip>
  </div>
</template>

<script>
import { filterObj } from "@/utils/util";
import { postAction, getAction } from "@/api/manage";
// import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { mixinDevice } from "@/utils/mixin";
import BlockModal from "./BlockModal";

import Map from "ol/Map";
import View from "ol/View";
import { LineString } from "ol/geom";
import Feature from "ol/Feature";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import { Draw, Modify, Snap } from "ol/interaction";
import { toString as geomToString } from "ol/geom/Geometry";
import { fromLonLat, toLonLat } from "ol/proj";
import { Fill, Stroke, Style, Icon, Circle, Text } from "ol/style";

import { transform } from "ol/proj"; //将坐标从源投影转换为目标投影。这将返回一个新坐标（并且不会修改原始坐标）。
import { defaults as defaultControls } from "ol/control";
import XYZ from "ol/source/XYZ";
import { getCenter } from "ol/extent";
import { Point, Polygon } from "ol/geom";

export default {
  name: "BlockGisModal",
  // mixins:[JeecgListMixin, mixinDevice],
  components: {
    // BlockModal
  },
  data() {
    return {
      isClear: false,

      title: "划地",
      visible: false,
      loading: false,

      map: null,
      //绘制线段上的长度，多边形中心面积
      source: null,
      vector: null,
      //当前绘制地块
      blockSource: null,
      blockLayer: null,
      //历史地块
      historyBlockSource: "",
      historyBlockLayer: "",

      draw: null,
      modify: null,
      snap: null,

      historyBlockList: [], //历史地块数据
      zc: "", //周长
      mus: "", //亩数
      zbxBh: "", //原始坐标集合
      zbx: "", //去掉闭合坐标的集合
      imgs: "",
      lonLat: [],
      coordinates: [],
    };
  },
  props: {
    // blockList: {
    //   type: [Array],
    //   required: false,
    // },
    isBack: {
      type: Boolean,
      required: false,
      default: false,
    },
    isShow: {
      type: Boolean,
      required: false,
      default: false,
    },
    isEndEdit: {
      type: Boolean,
      required: false,
      default: false,
    },
    isEdit: {
      type: Boolean,
      required: false,
      default: false,
    },
    number: {
      type: Number,
      required: false,
      default: 0,
    },
  },
  mounted() {
    this.initMap();
  },
  created() {
	this.getHistoryBlockList();
  },
  watch: {
    isEndEdit(newValue, oldValue) {
      this.isEndEdit = newValue;
      // console.log('props 中的 endEdit 发生变化:', newValue);
      // 在这里可以执行一些操作，比如根据新的值更新组件内部的数据
      if (this.isEndEdit) {
        // console.log("移除modify")
        this.map.removeInteraction(this.draw);
        this.map.removeInteraction(this.modify);
        this.map.removeInteraction(this.snap);
        this.isClear = false;
      }
    },
  },
  methods: {
	    getHistoryBlockList() {
      getAction('/wfim/wfimRegion/getDkZbx', {
        pageNo: 1,
        pageSize: 100,
      }).then((res) => {
        console.log('获取地块成功2：', res)
        let { code, message, result, success } = res
        if (code == 200 && result) {
          this.coordinates = result.coordinates;
          this.loadLandBoundary(this.coordinates);
        }
      })
    },
    //返回上一页
    goBack() {
      this.$router.back();
    },
    clearClick() {
      this.blockSource.clear();
      this.source.clear();
    },
    layerClick() {},
    rotateClick() {},

    /**
     * 初始化地图
     */
    initMap() {
      let centerLngLat = [76.000312737915, 39.473649532912]; //暂时定位
      let centerLngPos = transform(centerLngLat, "EPSG:4326", "EPSG:3857");
      const view = new View({
        center: centerLngPos,
        zoom: 16, // 设置初始化显示层级
        minZoom: 6, // 最小显示层级
        maxZoom: 18, // 最大显示层级
      });
      this.map = new Map({
        target: "olMap",
        view: view,
        controls: defaultControls({
          zoom: false,
          attribution: false,
          rotate: false,
        }),
      });

      // 添加底图
      let url = "http://t{0-7}.tianditu.com/DataServer?x={x}&y={y}&l={z}";
      url = `${url}&T=img_w&tk=2d0985c08a0f5ab1cd093f12417baf2d`;
      const sourceTdt = new XYZ({
        crossOrigin: "anonymous", //解决画布污染问题,不加就会报错
        url: url,
        projection: "EPSG:3857",
      });
      const tdtLayer = new TileLayer({
        source: sourceTdt,
      });
      this.map.addLayer(tdtLayer);
      // 添加注记
      url = "http://t{0-7}.tianditu.com/DataServer?x={x}&y={y}&l={z}";
      url = `${url}&T=cia_w&tk=2d0985c08a0f5ab1cd093f12417baf2d`;
      const sourceCIA = new XYZ({
        crossOrigin: "anonymous", //解决画布污染问题,不加就会报错
        url: url,
        projection: "EPSG:3857",
      });
      const tdtciaLayer = new TileLayer({
        source: sourceCIA,
      });
      this.map.addLayer(tdtciaLayer);

      //初始化地块图层
      this.initHistoryBlockLayer();
      this.initBlockLayer();
      this.initDrawLayer();

      // this.addInteraction()
    },
    initBlockLayer() {
      //创建空的矢量容器()
      this.blockSource = new VectorSource({});
      //创建图标层
      this.blockLayer = new VectorLayer({
        source: this.blockSource,
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)",
          }),
          stroke: new Stroke({
            color: "#ffcc33",
            width: 2,
          }),
          text: new Text({
            font: "12px Calibri,sans-serif",
            fill: new Fill({
              color: "#000",
            }),
            stroke: new Stroke({
              color: "#fff",
              width: 3,
            }),
          }),
        }),
      });

      this.map.addLayer(this.blockLayer);
    },
    initDrawLayer() {
      //创建空的矢量容器(point)
      this.source = new VectorSource({});
      //创建图标层
      this.vector = new VectorLayer({
        source: this.source,
        zIndex: 30,
      });

      this.map.addLayer(this.vector);
    },
    initHistoryBlockLayer() {
      //创建空的矢量容器(point)
      // console.log("进入初始化initHistoryBlockLayer")
      this.historyBlockSource = new VectorSource({});
      //创建图标层
      this.historyBlockLayer = new VectorLayer({
        source: this.historyBlockSource,
        zIndex: 30,
      });

      this.map.addLayer(this.historyBlockLayer);
    },

    loadLandBoundary(coordinates) {
      console.log("加载预设地块", coordinates);
      const landBoundaryFeature = new Feature({
        geometry: new Polygon(coordinates),
      });
      const landBoundarySource = new VectorSource({
        features: [landBoundaryFeature],
      });
      const landBoundaryLayer = new VectorLayer({
        source: landBoundarySource,
        style: new Style({
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.3)", // 设置白色半透明的背景颜色
          }),
          stroke: new Stroke({
            color: "red",
            width: 5,
          }),
        }),
      });
      this.map.addLayer(landBoundaryLayer);
    },
    //加载历史地块
    addHistoryBlock(block_list) {
      this.historyBlockSource.clear();
      // if(!this.isEdit){//编辑情况下不加载历史地块数据
      for (let i in block_list) {
        let blockInfo = block_list[i];
        if (blockInfo.zbxBh) {
          let arrs = JSON.parse(blockInfo.zbxBh); //不加这句话 不好使。。。
          let polygon = new Polygon(arrs);
          polygon.transform("EPSG:4326", "EPSG:3857");
          let feature = new Feature(polygon);
          let textInfo = blockInfo.name + "\n" + blockInfo.mj + "亩";
          let lineStyle = new Style({
            fill: new Fill({
              color: "rgba(255, 255, 255, 0.1)",
            }),
            stroke: new Stroke({
              color: "#3db4ff",
              width: 2,
            }),
            zIndex: 70,
            text: new Text({
              font: "13px Microsoft YaHei",
              text: textInfo,
              fill: new Fill({
                color: "#ffffff",
              }),
            }),
            image: new Circle({
              radius: 7,
              fill: new Fill({
                color: "#3db4ff",
              }),
            }),
          });
          // 添加线的样式
          feature.setStyle(lineStyle);
          //设置featureid
          feature.setId(blockInfo.id);
          // 添加线的fature
          this.historyBlockSource.addFeature(feature);
          //定位
          var center = getCenter(feature.getGeometry().getExtent());
          this.map.getView().setCenter(center); //设置当前地图的显示中心位置
        }
      }
      // }

      // const features11 = this.historyBlockSource.getFeatures();
      // for (let i = 0; i < features11.length; i++) {
      //   console.log(features11[i].getId());
      // }
    },
    moveViewChild(zbxBh) {
      let arrs = JSON.parse(zbxBh); //不加这句话 不好使。。。
      console.log(arrs);
      let polygon = new Polygon(arrs);
      polygon.transform("EPSG:4326", "EPSG:3857");
      let feature = new Feature(polygon);
      //定位
      var center = getCenter(feature.getGeometry().getExtent());
      console.log(center);
      this.map.getView().setCenter(center); //设置当前地图的显示中心位置
    },

    addInteraction(zbx_bh) {
      if (this.isEdit) {
        let arrs = JSON.parse(zbx_bh); //不加这句话 不好使。。。
        let polygon = new Polygon(arrs);
      
        polygon.transform("EPSG:4326", "EPSG:3857");
        let feature = new Feature(polygon);
        const geom = feature.getGeometry();
        const coordinates = geom.getCoordinates()[0];

        this.blockSource.clear();
        this.blockSource.addFeature(feature);

        this.source.clear();
        this.calculateLengthAndArea(coordinates);
      }
      if (!this.isEdit) {
        this.draw = new Draw({
          source: this.blockSource,
          type: "Polygon",
        });
        this.map.addInteraction(this.draw);
      }

      this.modify = new Modify({
        source: this.blockSource,
      });
      this.snap = new Snap({
        source: this.blockSource,
      });
      this.map.addInteraction(this.modify);
      this.map.addInteraction(this.snap);

      if (!this.isEdit) {
        this.draw.on("drawend", (event) => {
          const feature = event.feature;
          const geom = feature.getGeometry();
          const coordinates = geom.getCoordinates()[0];

          this.calculateZbx(coordinates);

          this.calculateLengthAndArea(coordinates);
          this.zc = this.calculatePerimeter(coordinates);
          // console.log(this.zc)
          this.lonLat = this.calculateCenter(coordinates);
          // console.log(this.lonLat)

          this.isClear = true;

          this.sendDataToParent();

          this.map.removeInteraction(this.draw);
        });
      }

      this.modify.on("modifystart", (event) => {
        // console.log("modifystart");
        this.source.clear();
      });
      this.modify.on("modifyend", (event) => {
        // console.log("modifyend");
        const features = event.features.getArray();
        if (features.length > 0) {
          for (let i = 0; i < features.length; i++) {
            const modifiedGeometry = features[i].getGeometry();
            if (modifiedGeometry.getType() === "Polygon") {
              const coordinates = modifiedGeometry.getCoordinates()[0]; // 获取修改后的多边形的坐标数组
              console.log('Modified coordinates:', coordinates);
              // 在这里可以对获取到的坐标数组进行处理
              this.calculateZbx(coordinates);
              this.calculateLengthAndArea(coordinates);
              this.zc = this.calculatePerimeter(coordinates);
              console.log(this.zc)
              this.lonLat = this.calculateCenter(coordinates);
              this.sendDataToParent();
              break;
            }
          }
        }
      });
    },
    calculateZbx(coordinates) {
      let coordinates4326 = this.convertCoordinates(coordinates);
      console.log(coordinates4326);
      this.zbx = this.changeZB(coordinates4326);
      console.log(this.zbx);
      this.zbxBh = JSON.stringify([coordinates4326]);
      console.log(this.zbxBh)
    },
    calculateLengthAndArea(coordinates) {
      // 遍历多边形的每条边
      for (let i = 0; i < coordinates.length - 1; i++) {
        const lineString = new LineString([coordinates[i], coordinates[i + 1]]);
        const length = lineString.getLength();

        const text = new Text({
          font: "12px Calibri,sans-serif",
          fill: new Fill({
            color: "#000",
          }),
          stroke: new Stroke({
            color: "#fff",
            width: 3,
          }),
          text: length.toFixed(2) + "m",
          placement: "line", // 设置文本的放置位置为沿着线段
          overflow: true, // 允许文本溢出
        });

        // 创建文本标签的样式
        const textStyle = new Style({
          text: text,
        });

        // 创建文本标签的要素
        const textFeature = new Feature({
          geometry: lineString,
        });
        textFeature.setStyle(textStyle);

        // 将文本标签的要素添加到地图上
        this.source.addFeature(textFeature);
      }
      let mj = 0;
      const polygon = new Polygon([coordinates]);
      mj = polygon.getArea();
      this.mus = (mj / 666.67).toFixed(2);
      // const acres = mj * 0.000247105 // Convert square meters to acres
      const center = getCenter(polygon.getExtent());
      const areaFeature = new Feature({
        geometry: new Point(center),
        name: this.mus + "亩",
      });
      const areaStyel = new Style({
        text: new Text({
          text: this.mus + "亩",
          font: "12px sans-serif",
          fill: new Fill({
            color: "blue",
          }),
          offsetY: 15,
        }),
      });
      areaFeature.setStyle(areaStyel);
      this.source.addFeature(areaFeature);
    },
    calculatePerimeter(coordinates) {
      let perimeter = 0;
      for (let i = 0; i < coordinates.length - 1; i++) {
        const startPoint = coordinates[i];
        const endPoint = coordinates[i + 1];
        perimeter += Math.sqrt(
          Math.pow(endPoint[0] - startPoint[0], 2) +
            Math.pow(endPoint[1] - startPoint[1], 2)
        );
      }
      return perimeter.toFixed(2);
    },
    calculateCenter(coordinates) {
      const centerX =
        coordinates.reduce((acc, coord) => acc + coord[0], 0) / coordinates.length;
      const centerY =
        coordinates.reduce((acc, coord) => acc + coord[1], 0) / coordinates.length;
      // return [centerX, centerY];
      return toLonLat([centerX, centerY]);
    },

    sendDataToParent() {
      const data = {
        mj: this.mus,
        areaReal: this.mus,
        lon: this.lonLat[0],
        lat: this.lonLat[1],
        zbx: this.zbx,
        zbxBh: this.zbxBh,
        zc: this.zc,
      };
      // console.log(data)
      this.$emit("send-data", data); // 触发名为 'send-data' 的自定义事件，并传递数据
    },
    // 处理坐标
    changeZB(list) {
      const startItem = list[0];
      const endItem = list[list.length - 1];
      if (startItem[0] === endItem[0] && startItem[1] === endItem[1] && list.length > 2) {
        // console.log('加载坐标处理', list)
        let returnData = "";
        for (let v = 0; v < list.length - 1; v++) {
          let item = list[v];
          returnData += `${item[0]} ${item[1]},`;
        }
        returnData = returnData.slice(0, -1);
        // console.log('returnData', returnData)
        return returnData;
      }
    },
    // 将3857坐标点数组转换为4326经纬度坐标数组
    convertCoordinates(coordinates3857) {
      let coordinates4326 = coordinates3857.map((coord) => toLonLat(coord));
      return coordinates4326;
    },
  },
};
</script>
<style lang="less" scoped>
#olMap {
  width: 100%;
  height: 100vh;
}

.buttonClass {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 5px;
  font-size: 12px;
  color: #666666;
  background-color: #eeeeee;
}

.but4 {
  position: absolute;
  top: 20px;
  right: 2%;
  z-index: 2;
  cursor: pointer;
  width: 40px;
  height: 40px;
}

.back2 {
  width: 20px;
  height: 20px;
}

.goback-but {
  position: absolute;
  top: 20px;
  left: 2%;
  z-index: 2;
  cursor: pointer;
  width: 40px;
  height: 40px;
}

.clear {
  position: absolute;
  top: 80px;
  right: 2%;
  z-index: 2;
  cursor: pointer;
  width: 40px;
  height: 40px;
}

.layer {
  position: absolute;
  bottom: 220px;
  right: 2%;
  z-index: 2;
  cursor: pointer;
  width: 40px;
  height: 40px;
}

.rotate {
  position: absolute;
  bottom: 160px;
  right: 2%;
  z-index: 2;
  cursor: pointer;
  width: 40px;
  height: 40px;
}

.scale {
  position: absolute;
  bottom: 50px;
  right: 2%;
  z-index: 2;
  cursor: pointer;
  width: 40px;
  height: 100px;
  line-height: 40px;
}

.back3 {
  width: 16px;
  height: 16px;
}
</style>
